package com.luoyx.vjsb.authority.security;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luoyx.vjsb.authority.security.exception.LoginFailLimitException;
import com.luoyx.vjsb.core.entity.SysUser;
import com.luoyx.vjsb.core.service.ISysUserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  处理用户登录前的准备
 * </p>
 *
 * @author luoyuanxiang
 * @date 2020/5/4 17:25
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ISysUserService  iSysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        String flagKey = "loginFailFlag:" + username;
        String value = stringRedisTemplate.opsForValue().get(flagKey);
        Long timeRest = stringRedisTemplate.getExpire(flagKey, TimeUnit.MINUTES);
        if (StrUtil.isNotBlank(value)) {
            // 超过限制次数
            throw new LoginFailLimitException("登录错误次数超过限制，请" + timeRest + "分钟后再试");
        }
        SysUser user = iSysUserService.getOne(new QueryWrapper<SysUser>().eq("username", username));
        if (user == null) {
            throw new UsernameNotFoundException("没有该用户！请重新输入！");
        }
        return new SecurityUserDetails(user);
    }
}
